package com.zj.study.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zj.study.model.User;
import com.zj.study.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.CoreSubscriber;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.UUID;

/**
 * @author ZhaoJiu
 * @since: 2021/7/19 19:09
 * @desc: webFlux 整合 MybatisPlus
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {


    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 添加用户
     *
     * @param user 用户实体
     * @return 相应结果
     */
    @PostMapping("save")
    public Mono<Boolean> saveUser(@RequestBody User user) {
        return Mono.just(userService.save(user));
    }

    /**
     * 用户名模糊查询
     *
     * @param username 用户名
     * @return 响应数据
     */
    @GetMapping("getByUsername")
    public Mono<List<User>> getByUsername(@RequestParam String username) {
        return Mono.just(userService.getByUsername(username))
                .switchIfEmpty(Mono.empty())
                .doOnError(e -> {
                    log.error("获取用户信息异常，异常信息: {}", e.getMessage());
                });
    }

    /**
     * 根据id 删除
     *
     * @param id 用户id
     * @return 响应信息
     */
    @DeleteMapping("delete/{id}")
    public Mono<ResponseEntity<Object>> deleteById(@PathVariable Long id) {

        return Mono.just(userService.getById(id))
                .switchIfEmpty(Mono.empty())
                .flatMap(user -> Mono.just(userService.removeById(user.getId()))
                        .then(Mono.just(new ResponseEntity<>(HttpStatus.OK)))
                );
    }

    /**
     * 查询所有
     *
     * @return Flux返回数据
     */
    @GetMapping("list")
    public Flux<User> list() {
        return Flux.fromIterable(userService.list());
    }

    /**
     * 查询所有
     *
     * @return Mono返回数据
     */
    @GetMapping("getList")
    public Mono<List<User>> lists() {
        return userService.getList();
    }

    /**
     * 分页查询
     *
     * @return 返回数据
     */
    @GetMapping("page")
    public Mono<Page<User>> pageMono() {
        return Mono.just(userService.page(new Page<>(1, 5)));
    }


    /**
     * 根据id查询
     *
     * @param userId 用户id
     * @return 用户数据
     */
    @GetMapping("{userId}")
    public Mono<User> findById(@PathVariable Long userId) {
        return Mono.just(userService.getById(userId));
    }


}
